var photos = {};

photos.Photo = function(entry) {
  this.entry = entry;
  this.src = entry.content.src;
  this.title = entry.title.$t;
  this.id = entry.gphoto$id.$t;
  this.etag = entry.gd$etag;
  this.albumId = entry.gphoto$albumid.$t;
  this.tags = [];
  this.thumbNails = {};
  for(var idx =0; idx < entry.media$group.media$thumbnail.length; idx++) {
      this.thumbNails[entry.media$group.media$thumbnail[idx].height] = entry.media$group.media$thumbnail[idx];
  }
  this.link = {
    'communityPhotos': util.getLink(entry.link, 'alternate').href,
    'myPhotos': util.getLink(entry.link, 'alternate').href.replace('psc=G', 'psc=S')
  };
};

/**
 * Callback for processing the JSON feed returned by the DocList API.
 * @param {string} response The server's response.
 * @param {XMLHttpRequest} xhr The xhr request that was made.
 */
photos.processResults = function(response, xhr) {
  if (xhr.status != 200) {
    util.handleError(xhr, response);
    return;
  } else {
    requestFailureCount = 0;
  }

  var data = JSON.parse(response);

  for (var i = 0, entry; entry = data.feed.entry[i]; ++i) {
    var photo = new photos.Photo(entry);
    bgPage.photos[photo.id] = photo;

    var found = false;
    for(var idx = 0; idx < bgPage.selectedPhotoUrls.length; idx++) {
	if (bgPage.selectedPhotoUrls[idx].split('/')[8] == photo.src.split('/')[7]) {
	    found = true;
	}
    }
    if (found) {
        bgPage.selectedPhotos[photo.id] = photo;
    }

  }

  var nextLink = util.getLink(data.feed.link, 'next');
  if (nextLink) {
    gdocs.getDocumentList(nextLink.href); // Fetch next page of results.
  } else {
    var keys = Object.keys(bgPage.selectedPhotos);
    for(var idx =0; idx < keys.length; idx++) {
            var photoId = keys[idx];
            var photo = bgPage.selectedPhotos[photoId];
	    tags.getDocumentList("https://picasaweb.google.com/data/feed/api/user/default/albumid/" + photo.albumId + "/photoid/" + photoId + "?kind=tag&access=all&alt=json", tags.processPhotoTagListResults);

    }
    tags.renderDocList();
    photos.renderDocList();
  }
};

/**
 * Presents the in-memory documents that were fetched from the server as HTML.
 */
photos.renderDocList = function() {
  util.hideMsg();

  var keys = Object.keys(bgPage.selectedPhotos);
  for (var idx = 0; keys.length; idx++) {
    var photo = bgPage.selectedPhotos[keys[idx]];
    var img = $('<img/>')
	               .attr('src', photo.thumbNails[Math.min.apply(null, Object.keys(photo.thumbNails))].url)
	               .attr('title', photo.title);

    $('#photos').append(img);
  }
};

/**
 * Fetches the user's document list.
 * @param {string?} opt_url A url to query the doclist API with. If omitted,
 *     the main doclist feed uri is used.
 */
photos.getDocumentList = function(opt_url) {
  var url = opt_url || null;

  var params = {
    'headers': {
      'GData-Version': '3.0'
    }
  };

  if (!url) {
    util.displayMsg('Fetching your tags');

    bgPage.photos = []; // Clear document list. We're doing a refresh.

    url = bgPage.DOCLIST_FEED;
    params['parameters'] = {
      'alt': 'json'
    };
  } else {
    util.displayMsg($('#butter').text() + '.');

    var parts = url.split('?');
    if (parts.length > 1) {
      url = parts[0]; // Extract base URI. Params are passed in separately.
      params['parameters'] = util.unstringify(parts[1]);
    }
  }

  bgPage.oauth.sendSignedRequest(url, photos.processResults, params);
};


